using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;

namespace CodeStory.WebControls
{
	public class StateTemplateCollection : ICollection, IStateManager
	{
		private bool isTrackingViewState;
		private List<StateTemplate> list;

		internal StateTemplateCollection() {
			list = new List<StateTemplate>(4);
		}

		public StateTemplate this[int index] {
			get { return list[index]; }
			set { list[index] = value; }
		}

		public bool IsTrackingViewState {
			get { return isTrackingViewState; }
		}

		#region ICollection Members
		public void CopyTo(Array array, int index) {
			((ICollection)list).CopyTo(array, index);
		}

		public int Count {
			get { return list.Count; }
		}
		public object SyncRoot {
			get { return ((ICollection)list).SyncRoot; }
		}
		public bool IsSynchronized {
			get { return ((ICollection)list).IsSynchronized; }
		}

		public IEnumerator GetEnumerator() {
			foreach (StateTemplate t in list) {
				yield return t;
			}
		}
		#endregion

		#region IStateManager Members
		bool IStateManager.IsTrackingViewState {
			get { return IsTrackingViewState; }
		}

		void IStateManager.LoadViewState(object state) {
			LoadViewState(state);
		}

		object IStateManager.SaveViewState() {
			return SaveViewState();
		}

		void IStateManager.TrackViewState() {
			TrackViewState();
		}
		#endregion

		public void Add(StateTemplate item) {
			AddAt(this.Count, item);
		}

		private void AddAt(int index, StateTemplate item) {
			list.Insert(index, item);
			if (this.isTrackingViewState) {
				((IStateManager)item).TrackViewState();
			}
		}

		internal void Clear() {
			list.Clear();
		}

		public void Remove(StateTemplate value) {
			if (value == null) {
				throw new ArgumentNullException("value");
			}
			int index = this.list.IndexOf(value);
			if (index != -1) {
				this.RemoveAt(index);
			}
		}

		private void RemoveAt(int index) {
			StateTemplate node = this[index];
			this.list.RemoveAt(index);
		}

		public void LoadViewState(object state) {
			if (state == null) return;
			object[] ar = (object[])state;
			foreach (object o in ar) {
				StateTemplate t = new StateTemplate();
				t.LoadViewState(o);
				list.Add(t);
			}
		}

		public object SaveViewState() {
			object[] ar = new object[Count];
			bool flag = false;
			int i = 0;
			foreach (StateTemplate state in list) {
				ar[i] = state.SaveViewState();
				if (ar[i] != null) {
					flag = true;
				}
				i++;
			}
			if (!flag) {
				return null;
			}
			return ar;
		}

		public void TrackViewState() {
			isTrackingViewState = true;
		}
	}
}